#include "task_w6100_net_status_check.h"

#include "FreeRTOS.h"
#include "task.h"

#include "device_resource.h"
#include "print_rtt.h"
#include "w6100.h"
#include "w6100_dhcp.h"
#include "w6100_init.h"
// #include "rtl_private_op.h"

static StackType_t xW6100StatusCheckStack[256]; // 静态栈
static StaticTask_t xW6100StatusCheckTCB;       // 静态 TCB（可选，省堆）
// typedef enum
// {
//   W6100_INIT = 0x00,
//   W6100_DHCP,
//   W6100_DHCP_TIMEOUT,
//   W6100_READ,
//   W6100_READ_TO_REINIT,

// } W6100_STATUS_DPT;
static void vW6100StatusCheckTaskEntry(void *pvParameters)
{
  int ret;
  w6100_net_status = 0;
  (void)pvParameters;
  for (;;)
  {
    switch (w6100_net_status)
    {
    case W6100_INIT:
      Set_Network();
      if (setting_para->port1_DHCPV4_FLAG == 1)
      {
        init_dhcp_client();
        w6100_net_status = W6100_DHCP;
        break;
      }
      w6100_net_status = W6100_READY;
      break;
    case W6100_DHCP:
      ret = check_DHCP_state();
      switch (ret)
      {
      case DHCP_RET_UPDATE:
        dhcp_set_network();
        MQTT_connet_status = MQTT_DISCONNECT;
        w6100_net_status = W6100_READY;
        break;
      case DHCP_RET_TIMEOUT:
      case DHCP_RET_CONFLICT:
        net_config->eth0_dhcp_flag = ret;
        w6100_net_status = W6100_DHCP_FAIL;
      default:
        break;
      }
      break;
    case W6100_READY:
      if (setting_para->port1_DHCPV4_FLAG == 1)
      {
        ret = check_DHCP_state();
        switch (ret)
        {
        case DHCP_RET_UPDATE:
          dhcp_set_network();
          MQTT_connet_status = MQTT_DISCONNECT;
          w6100_net_status = W6100_READY;
          break;
        case DHCP_RET_TIMEOUT:
        case DHCP_RET_CONFLICT:
          net_config->eth0_dhcp_flag = ret;
          MQTT_connet_status = MQTT_DISCONNECT;
          w6100_net_status = W6100_DHCP_FAIL;
        default:
          break;
        }
      }
      break;
    case W6100_DHCP_FAIL:
      LOG_INFO("DHCP fail\r\n");
    default:
      break;
    }
    dhcp_time++;
    vTaskDelay(pdMS_TO_TICKS(1000));
  }
}

void vW6100StatusCheckTaskCreate(void)
{
  TaskHandle_t xHandle = NULL;

  taskENTER_CRITICAL(); // 进入临界区
  /* 创建system_led任务 - 静态方法 */
  xHandle = xTaskCreateStatic(
      (TaskFunction_t)vW6100StatusCheckTaskEntry,                     /* 任务入口函数 */
      (const char *)"W6100 status",                                   /* 任务名字 */
      (uint16_t)sizeof(xW6100StatusCheckStack) / sizeof(StackType_t), /* 任务栈大小 */
      (void *)NULL,                                                   /* 任务入口函数参数 */
      (UBaseType_t)5,                                                 /* 任务的优先级 */
      (StackType_t *)xW6100StatusCheckStack,                          /* 静态栈数组 */
      (StaticTask_t *)&xW6100StatusCheckTCB);                         /* 静态TCB的地址 */

  if (xHandle != NULL)
  {
    LOG_INFO("Create W6100 status check task success!\r\n");
  }
  taskEXIT_CRITICAL(); // 退出临界区，无论成功失败都要退出
}
